package com.hejia.bulbul.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.hejia.alauda.entity.Links;
import com.hejia.alauda.entity.Popularize;
import com.hejia.alauda.entity.PopularizeCategory;
import com.hejia.alauda.entity.PopularizePlan;
import com.hejia.alauda.service.AccountService;
import com.hejia.alauda.service.PageService;
import com.hejia.alauda.service.PopularizeService;
import com.hejia.alauda.utils.Pager;
import com.hejia.alauda.utils.PagerHelper;

/**
 * 推广控制器
 * 
 * @author hyr
 *
 */
@Controller
@RequestMapping("popularizes")
public class PopularizeController extends BaseController {

	@Value("#{settings['popularize.rootUrl']}")
	private String popularizeRootUrl;

	@Resource
	private PopularizeService popularizeService;

	@Resource
	private PopularizeService popularizeCatogeryService;

	@Resource
	private PopularizeService popularizePlanService;

	@Resource
	private PageService linksService;

	@Resource
	private AccountService accountService;

	@RequestMapping()
	public String list(String name, Boolean isAllPopularizing,
			Pager<Popularize> pager, ModelMap model) {

		if (isAllPopularizing == null) {
			isAllPopularizing = false;
		}

		pager = this.popularizeService.findPopularizes(name, isAllPopularizing,
				pager);

		PagerHelper<Popularize> helper = new PagerHelper<>();
		helper.setPager(pager);
		Map<String, String> map = new HashMap<>();
		if (name != null) {
			map.put("name", name);
		}
		if (isAllPopularizing != null) {
			map.put("isAllPopularizing", isAllPopularizing.toString());
		}
		helper.setParams(map);
		helper.setBaseUrl("/popularizes");

		model.put("pagerHelper", helper);
		model.put("popularizeRootUrl", popularizeRootUrl);
		model.put("name", name);
		model.put("isAllPopularizing", isAllPopularizing);
		model.put("popularizes", pager);

		return "popularize/list";
	}

	@RequestMapping("add")
	public String add(ModelMap model) {

		List<PopularizeCategory> categorys = this.popularizeCatogeryService
				.findSmallerCategorys();
		model.put("categorys", categorys);

		return "popularize/add";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String add(Popularize popularize, ModelMap model) {

		try {
			if (!popularize.getUrl().startsWith("http")) {
				List<PopularizeCategory> categorys = this.popularizeCatogeryService
						.findSmallerCategorys();
				model.put("error", "推广地址缺少http开头");
				model.put("popularize", popularize);
				model.put("categorys", categorys);
				return "popularize/add";
			} else {
				UserDetails currentAccount = this.accountService
						.getCurrentAccount();
				if (currentAccount != null) {
					popularize.setEditor(currentAccount.getUsername());
				}
				this.popularizeService.add(popularize);
				return "redirect:/popularizes";
			}
		} catch (Exception e) {
			List<PopularizeCategory> categorys = this.popularizeCatogeryService
					.findSmallerCategorys();
			model.put("error", "添加推广失败");
			model.put("popularize", popularize);
			model.put("categorys", categorys);
			return "popularize/add";
		}
	}

	@RequestMapping("{id}/edit")
	public String edit(@PathVariable long id, ModelMap model) {

		Popularize popularize = this.popularizeService.findById(id);
		List<PopularizeCategory> categorys = this.popularizeCatogeryService
				.findSmallerCategorys();

		model.put("popularize", popularize);
		model.put("categorys", categorys);

		return "popularize/edit";
	}

	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public String update(Popularize popularize, ModelMap model) {

		try {
			if (!popularize.getUrl().startsWith("http")) {
				List<PopularizeCategory> categorys = this.popularizeCatogeryService
						.findSmallerCategorys();
				popularize.setCategory(this.popularizeCatogeryService
						.findCategoryById(popularize.getCategory().getId()));
				model.put("error", "推广地址缺少http开头");
				model.put("popularize", popularize);
				model.put("categorys", categorys);
				return "popularize/edit";
			} else {
				UserDetails currentAccount = this.accountService
						.getCurrentAccount();
				String operator = null;
				if (currentAccount != null) {
					operator = currentAccount.getUsername();
				}
				this.popularizeService.update(popularize, operator);
				return "redirect:/popularizes";
			}
		} catch (Exception e) {
			List<PopularizeCategory> categorys = this.popularizeCatogeryService
					.findSmallerCategorys();
			popularize.setCategory(this.popularizeCatogeryService
					.findCategoryById(popularize.getCategory().getId()));
			model.put("error", "更新推广失败");
			model.put("popularize", popularize);
			model.put("categorys", categorys);
			return "popularize/edit";
		}
	}

	@RequestMapping("{id}")
	public String detail(@PathVariable long id, ModelMap model) {

		Popularize popularize = this.popularizeService.findById(id);
		List<PopularizePlan> plans = this.popularizePlanService
				.findPlansByPopularizeId(popularize.getId());

		model.put("popularizeRootUrl", popularizeRootUrl);
		model.put("popularize", popularize);
		model.put("plans", plans);

		return "popularize/detail";
	}

	/**
	 * 友情链接列表
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "linkslist", method = RequestMethod.GET)
	public String linksList(ModelMap model) {
		List<Links> list = linksService.getParameters();
		model.put("list", list);
		return "popularize/linkslist";
	}

	/**
	 * 友情链接添加界面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "linksadd", method = RequestMethod.GET)
	public String linksAdd(ModelMap model) {
		return "popularize/linksadd";
	}

	/**
	 * 友情链接保存
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "linksadd", method = RequestMethod.POST)
	public String saveLinksList(Links links, ModelMap model,
			RedirectAttributes redirectAttributes) {

		links.setCreateDate(new Date());
		links.setModifyDate(new Date());
		if (linksService.saveLinks(links)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "友情链接添加成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "友情链接添加失败");
		}

		return "redirect:/popularizes/linkslist";
	}

	/**
	 * 跳转到友情链接修改界面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "linksupdate/{id}", method = RequestMethod.GET)
	public String linksUpdate(@PathVariable Long id, ModelMap model) {
		Links links = linksService.getLinksById(id);
		model.put("links", links);
		return "popularize/linksadd";
	}

	@RequestMapping(value = "linksupdate/{id}", method = RequestMethod.POST)
	public String saveUpdateLinksList(@PathVariable Long id, Links links,
			ModelMap model, RedirectAttributes redirectAttributes) {

		Links links2 = linksService.getLinksById(id);
		links2.setModifyDate(new Date());
		links2.setName(links.getName());
		links2.setUrl(links.getUrl());
		links2.setDisplay(links.getDisplay());
		links2.setMemo(links.getMemo());

		if (linksService.updateLinks(links2)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "友情链接修改成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "友情链接修改失败");
		}

		return "redirect:/popularizes/linkslist";
	}

	/**
	 * 删除友情链接
	 * 
	 * @param id
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */

	@RequestMapping(value = "linksdelete/{id}", method = RequestMethod.GET)
	public String deleteLinksList(@PathVariable Long id, ModelMap model,
			RedirectAttributes redirectAttributes) {
		if (linksService.deleteLinks(id)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "友情链接删除成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "友情链接删除失败");
		}

		return "redirect:/popularizes/linkslist";
	}

}
